﻿var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = 'login';
}
// Get Value CheckBox
jQuery.fn.getCheckboxVal = function () {
    var vals = [];
    var i = 0;
    this.each(function () {
        vals[i++] = jQuery(this).val();
    });
    return vals;
}
// Get Value CheckBox

// Get name CheckBox
jQuery.fn.getCheckboxName = function () {
    var names = [];
    var i = 0;
    this.each(function () {
        names[i++] = jQuery(this).attr('name');
    });
    return names;
}
// Get name CheckBox

$(document).ready(function () {

    // Get Info User Login
    $.ajax({
        url: gb_servicePath + '/authenticateduser/ID/' + userId + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var admin = data.ReturnData;
                $('#p_first_last span').html(admin.FirstName + ' ' + admin.LastName);
                $('.username').html(admin.FirstName + ' ' + admin.LastName);
                $('#p_phone_number span').html(admin.PhoneNumber);
                $('#p_username span').html(admin.UserName);
                $('#p_time_zone span').html(admin.TimeZoneID);
                $('#p_enterprise span').html(admin.CompanyBrandInfo.CompanyInfo.Name);
                $('#p_brand_name span').html(admin.CompanyBrandInfo.BrandInfo.Name);
                $('.brandname').html(admin.CompanyBrandInfo.BrandInfo.Name);
                if ((admin.UserRoles != null) && (admin.UserRoles[0] != null) && (admin.UserRoles[0].Name == "SuperAdmin")) {
                    $('.content_top .i_edit').attr('href', '../Profile/ProfileAdmin?ref=' + getCurrentPage());

                }
                if ((admin.UserRoles != null) && (admin.UserRoles[0] != null) && (admin.UserRoles[0].Name == "SoliAdmin")) {
                    $('.content_top .i_edit').attr('href', '../Profile/EditProfile?ref=' + getCurrentPage());
                    window.location.href = 'AdminDash';
                }
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in /authenticateduser/ID/' + userId + '.json ->" + xerror);
            }
        }
    });
    //Get Details User by id
    //get Admin detail
    $("#cb_user").change(function () {
        $('#tr_username').removeClass('hide');
        if ($(this).children(":selected").attr("name") == "0") {
            var o = $('#new_super_admin');
            $(o).find('#first_name_sum_new').html('');
            $(o).find('#last_name_sum_new').html('');
            $(o).find('#email_sum_new').html('');
            $(o).find('#phone_sum_new').html('');
            $(o).find('#username_sum_new').html('');
            $(o).find('#lbl_username_new').html('');
            $(o).find('#timezone_sum_new').html('');
            $('#cb_timezone option[name=0]').attr("selected", "selected");
            $('#timezone_selection .customStyleSelectBoxInner').html($('#cb_timezone option[name=0]').val());

        } else {
            GetDetailsUser($(this).children(":selected").attr("name"));
            $('.controls_new').addClass('hide');
            $('.lbl_new').removeClass('hide');
        }
    });

    $('#edit_super_admin .i_delete').click(function (e) {
        var campainid = $('#cb_edit_camp').children(":selected").attr("name");
        if (campainid == "0") {
            alert('Please select a campain');
        }
        else {
            $("#box_delete_campain").modal({
                opacity: 80,
                overlayCss: { backgroundColor: "#000" }
            });
            $('#btn_delete_camp').addClass('campain_edit').removeClass('campain_new');
        }
        //return false;
    });
    $('#new_super_admin .i_delete').click(function (e) {
        var campainid = $('#cb_camp').children(":selected").attr("name");
        if (campainid == "0") {
            alert('Please select a campain');
        }
        else {
            $("#box_delete_campain").modal({
                opacity: 80,
                overlayCss: { backgroundColor: "#000" }
            });
            $('#btn_delete_camp').addClass('campain_new').removeClass('campain_edit');
        }
        //return false;
    });

    $('#btn_delete_camp').click(function () {
        if ($(this).hasClass('campain_new')) {
            var campainid = $('#cb_camp').children(":selected").attr("name");
        }
        else if ($(this).hasClass('campain_edit')) {
            var campainid = $('#cb_edit_camp').children(":selected").attr("name");
        }

        deleteCampain(campainid);


    });

    function deleteCampain(id) {
        $.ajax({
            url: gb_servicePath + 'campaign/delete/' + id + '.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    getListCampain();
                    $.modal.close();
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in campaign/delete/" + id + ".json ->" + xerror);
                }
            }
        });
    }

    $('#i_editUser').click(function () {
        var id = $("#cb_user option:selected").attr("name");
        if (id == "0") {
            alert('please select a user');
        }
        else {
            showNewAdmin2(id);
        }
    });
    function GetDetailsUser(id) {
        $.ajax({
            url: gb_servicePath + '/authenticateduser/ID/' + id + '.json',
            crossDomain: "true",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    var admin = data.ReturnData;
                    var o = $('#new_super_admin');
                    $(o).find('#first_name_sum_new').html(admin.FirstName);
                    $(o).find('#last_name_sum_new').html(admin.LastName);
                    //$(o).find('#campaign_name_sum_new').html('Campaign Name');
                    $(o).find('#email_sum_new').html(admin.EmailAddress);
                    $(o).find('#phone_sum_new').html(admin.PhoneNumber);
                    $(o).find('#username_sum_new').html(admin.UserName);
                    $(o).find('#lbl_username_new').html(admin.UserName);
                    $(o).find('#timezone_sum_new').html(admin.TimeZoneID);
                    $(o).find('#ddl_user_new.user_view option[name=' + admin.UserRoles[0].RoleType + ']').attr("selected", "selected");
                    $(o).find('.ddl_user_new.user_view .customStyleSelectBoxInner').html($('#ddl_user_new option[name=' + admin.UserRoles[0].RoleType + ']').val());

                    $(o).find('.for_new .label_check').removeClass('c_on');
                    $(o).find('.for_new .list_count input').attr('checked', false);

                    if (admin.CampaignRoleCountryInfo != "") {
                        $('#cb_camp option[name=' + admin.CampaignRoleCountryInfo[0].CampaignRoleInfo.CampaignInfo.Id + ']').attr("selected", "selected");
                        $('.ddlCampaign .customStyleSelectBoxInner').html(admin.CampaignRoleCountryInfo[0].CampaignRoleInfo.CampaignInfo.Name);
                        $.each(admin.CampaignRoleCountryInfo, function (i, val) {
                            $.each(val.CountryList, function (i, val_country) {
                                $(o).find('.for_new.user_view #country' + val_country.Id + ' .label_check').addClass('c_on');
                                $(o).find('.for_new.user_view .list_count input[name=' + val_country.Id + ']').attr('checked', true);
                            });
                        });
                    }
                    else {
                        $('#cb_camp option[name=0]').attr("selected", "selected");
                        $('.ddlCampaign .customStyleSelectBoxInner').html($('#cb_camp option[name=0]').val());
                    }

                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in /authenticateduser/ID/" + id + ".json ->" + xerror);
                }
            }
        });
    }

    // Get List User Campain
    function getListCampain() {
        $("#camp_selection").find("select").append("<option name='0'>Select Campain</option>");
        $(".select_short4.ddlCampaign").find(".customStyleSelectBoxInner").html('Select Campain');
        $("#camp_edit_selection").find("select").append("<option name='0'>Select Campain</option>");
        $(".select_short4.ddlCampaign_edit").find(".customStyleSelectBoxInner").html('Select Campain');
        $.ajax({
            url: gb_servicePath + '/campaign/list/summary.json',
            crossDomain: "true",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $.each(data.ReturnData, function (i, val) {
                        var o1 = $("<option name='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                        var o2 = $("<option name='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                        $("#camp_selection").find("select").append(o1);
                        $("#camp_edit_selection").find("select").append(o2);
                    });
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in authenticateduser/list/summary.json ->" + xerror);
                }
            }
        });
    }
    // Get List User
    function getListUser() {
        $("#user_selection").find("select").append("<option name='0'>Select User</option>");
        $(".select_short4.ddlUser").find(".customStyleSelectBoxInner").html('Select User');
        $.ajax({
            url: gb_servicePath + '/authenticateduser/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $.each(data.ReturnData, function (i, val) {
                        var o = $("<option name='" + val.Id + "' value='" + val.FirstName + ' ' + val.LastName + "' >" + val.FirstName + ' ' + val.LastName + "</option>");
                        $("#user_selection").find("select").append(o);
                    });
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in authenticateduser/list/summary.json ->" + xerror);
                }
            }
        });
    }

    // Get List Time Zone
    function getListTimeZone() {
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                                $(".select_time").find(".customStyleSelectBoxInner").html(val.Timezone.Name);

                                var o2 = $("<option selected='selected' name='" + val.Timezone.Id + "' id='tznew" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                                $(".select_time").find(".customStyleSelectBoxInner").html(val.Timezone.Name);
                            } else {
                                var o = $("<option name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                                var o2 = $("<option name='" + val.Timezone.Id + "' id='tznew" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");

                            }
                            if ($("#tz" + val.Timezone.Id).length == 0) {
                                $("#timezone_selection").find("select").append(o);
                            }
                            if ($("#tznew" + val.Timezone.Id).length == 0) {
                                $("#timezone_selection_new").find("select").append(o2);
                            }
                        });
                    }
                });
    }
    // get selected countries
    function getCountries() {
        var arr = new Array();
        $("#countries_campaign .c_on").each(function () {
            arr.push($(this).attr('id'));
        });

        return arr;
    }
    var idlangselected = '0';

    // Get Function Get List Countries and Language
    function getListCountriesBoxLang() {
        // get Country is Selected
        var arrayCountries = new Array();
        arrayCountries = getCountries();
        $("#list_country_temp").css("display", "none");
        //        if ($(".mk_kw_r").hasClass("hide")) {
        //            $(".mk_kw_r").removeClass("hide");
        //        }
        //        else {
        //            $(".mk_kw_r").addClass("hide");
        //        }
        if (!$(".mk_kw_r").hasClass("hide")) {

            var arrcountry = new Array();
            for (var i = 0; i < arrlanguage.length; i++) {
                arrcountry = arrcountry.concat(arrlanguage[i].countries);
            }
            $("#list_country .item_country").each(function () {
                for (var i = 0; i < arrcountry.length; i++) {

                    if ($(this).attr("id") == arrcountry[i]) {
                        $(this).removeClass('c_on');
                        $(this).addClass('c_disable');
                        $(this).find("input").removeAttr('checked');
                        $(this).find("input").attr('disabled', 'disabled');

                    }
                }
            });
        }
        if (idlangselected == '0') {
            $(".mk_kw_r").addClass("hide")
        }
        $("#list_lang_temp").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        //var strLangIdAdded = "";
                        //var langId;
                        $('.item_lang').remove();
                        var ishiden = true;
                        $.each(json1.ReturnData, function (i, val) {
                            // check if alredy add country in combobox
                            //                            if ($("#country_" + val.Country.Id).length == 0) {
                            //                                var o = $("#list_country_temp").clone();
                            //                                $(o).css("display", "block");
                            //                                $(o).find("input").attr("value", val.Country.Id);
                            //                                $(o).find("input").attr("name", val.Country.Name);
                            //                                $(o).attr("id", "country_" + val.Country.Id);
                            //                                $(o).find("span").html(val.Country.Name);
                            //                                $("#list_country").append(o);
                            //                                langId = val.Language.Id;
                            //                            }
                            //if (strLangIdAdded.indexOf(langId) < 0) {
                            //hasn't added langId yet


                            for (var i = 0; i < arrayCountries.length; i++) {
                                if (parseInt(val.Country.Id, '10') == parseInt(arrayCountries[i], '10')) {
                                    var olag = $("#list_lang_temp").clone();
                                    olag.css("display", "block");
                                    olag.addClass('item_lang');
                                    olag.find("input").attr("value", val.Language.Id);
                                    olag.find("input").attr("id", val.Language.Name);
                                    olag.attr("id", "lang_" + val.Country.Id);
                                    olag.find("input").addClass("radio_lang");
                                    olag.find("span").html(val.Language.Name);
                                    if (ishiden) {
                                        if (parseInt(idlangselected, '10') == parseInt(val.Language.Id, '10')) {

                                            ishiden = false;
                                        }
                                    }
                                    for (var j = 0; j < arrlanguage.length; j++) {

                                        if (arrlanguage[j].lang == val.Language.Id) {

                                            if (arrlanguage[j].disable) {
                                                olag.removeClass('c_on');
                                                olag.addClass('c_disable');
                                                olag.find("input").removeAttr('checked');
                                                olag.find("input").attr('disabled', 'disabled');
                                            }
                                            else {
                                                olag.addClass('r_on');
                                                olag.find("input").attr('checked', true);
                                            }
                                        }
                                    }
                                    $("#list_lang").append(olag);
                                    //strLangIdAdded += langId + ";";
                                }

                            }

                        });
                        if (ishiden) {
                            $(".mk_kw_r").addClass("hide");
                        }

                        $('.radio_lang').click(function (e) {
                            idlangselected = $(this).val();
                            //                            for (var k = 0; k < arrlanguage.length; k++) {
                            //                                if($(this).val()==)
                            //                            }

                            $(".mk_kw_r").removeClass("hide");
                            getListCountriesByLang($(this).val());
                        });

                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        setupLabel();
                        $('.list_countries').jScrollPane();
                    }
                });
    }
    // End Get Function Get List Countries
    // get list countries by language is selected
    function getListCountriesByLang(idlang) {
        $("#list_country_temp").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $('.item_country').remove();
                        $.each(json1.ReturnData, function (i, val) {
                            //check if alredy add country in combobox
                            if (parseInt(val.Language.Id, '10') == parseInt(idlang, '10')) {
                                var o = $("#list_country_temp").clone();
                                $(o).css("display", "block");
                                $(o).addClass('item_country');
                                $(o).find("input").attr("value", val.Country.Id);
                                $(o).removeClass('c_on');
                                $(o).find("input").removeAttr('checked');
                                $(o).find("input").attr("name", val.Country.Name);
                                $(o).attr("id", "country_" + val.Country.Id);
                                $(o).find("span").html(val.Country.Name);

                                $("#list_country").append(o);
                            }
                        });

                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        setupLabel();
                    }
                }
         );
    }

    $('#txtcolor').bind('keyup', function () {
        $(this).ColorPickerSetColor(this.value);
        $('#colorSelector div').css('backgroundColor', this.value);
    });

    $('#txtcolor2').bind('keyup', function () {
        $(this).ColorPickerSetColor(this.value);
        $('#colorSelector2 div').css('backgroundColor', this.value);
    });



    //Scroll textarea
    /*$('#txtCampDesc').jScrollPane({ animateScroll: true });
    $('#txtCampDesc').keypress(function () {
    if (this.height() > 40) {
    $(this).jScrollPane({ animateScroll: true });
    }
    });*/

    /*All function for Admin List */
    var arrData = new Array(); // all infomation get from service
    var selectedRowKey = ""; // row's id is current selected in list 

    // Admin Dask List view
    $('.form_rows-border').find('img').css('visibility', 'hidden');
    // Json: Get Admin List
    function GetListAdmin() {
        arrData.splice(0, arrData.length);
        $.ajax({
            url: gb_servicePath + '/authenticateduser/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $.each(data.ReturnData, function (i, val) {
                        var o = new Object();
                        //Id
                        o.id = val.Id;
                        //Enterprise 
                        var enterprises;
                        var campigns;
                        var brands;
                        $.each(val.CampaignRoleCountryInfo, function (i, val_info) {
                            enterprises = val_info.CampaignRoleInfo.CampaignInfo.Brand.Company.Name;
                            campigns = val_info.CampaignRoleInfo.CampaignInfo.Name;
                            brands = val_info.CampaignRoleInfo.CampaignInfo.Brand.Name;

                        });
                        o.enterprise = enterprises;
                        //Brand
                        o.brand = brands;
                        //Role 
                        if (val.UserRoles != null && val.UserRoles.length > 0) {
                            for (i = 0; i < val.UserRoles.length; i++) {
                                if (i + 1 == val.UserRoles.length) { // Last item
                                    o.role = val.UserRoles[i].Name;
                                } else {
                                    o.role = val.UserRoles[i].Name + "; ";
                                }
                            }

                        } else {
                            o.role = ""; // Not has any role
                        }

                        //Status
                        if (val.ApprovalStatus == 1) {
                            o.status = "true";
                        }
                        else {
                            o.status = "false";
                        }
                        //Name
                        o.name = val.LastName + ", " + val.FirstName;
                        //Campaign
                        o.campaign = campigns;
                        //Email
                        o.email = val.EmailAddress;

                        //Username
                        o.username = val.UserName;
                        arrData.push(o);
                    });
                    // Call bind Data function to List
                    bindData();
                    SortAdminFilter("enterprise", 1);
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in authenticateduser/list/summary.json ->" + xerror);
                }
            }
        });
    }
    // End Json: Get Admin List

    // Bind Data
    function bindData() {

        $(".list_row_users").find("img").hide();
        $(".list_row_users").find(".rows_users").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#rows_users_temp").clone();
            $(o).attr("id", arrData[i].id);
            if (i % 2 == 1) {
                $(o).addClass("users_alt");
            }
            $(o).removeClass("item_temp");
            $(o).find(".col_enterprise").html(arrData[i].enterprise);
            $(o).find(".col_brand").html(arrData[i].brand);
            $(o).find(".col_role").html(arrData[i].role);
            if (arrData[i].status == "true") {
                $(o).find(".col_status").html('Active');
            } else {
                $(o).find(".col_status").html('Inactive');
            }
            $(o).find(".colo_name").html(arrData[i].name);
            $(o).find(".colo_campaign").html(arrData[i].campaign);
            $(o).find(".colo_email").html(arrData[i].email);
            $(o).find(".col_username").html(arrData[i].username);

            if (selectedRowKey == arrData[i].id.toString()) {
                $(o).addClass('rows_alert_hover');
                $(o).find('.bar').removeClass("hide");
            }

            if ($(".list_row_users").find(".jspPane").size() == 0) {
                $(".list_row_users").append(o);
            } else {
                $(".list_row_users").find(".jspPane").append(o);
            }
        }

        /*$('.rows_users').click(function () {
        selectedRowKey = $(this).attr("id");
        alert(1);
        alert(selectedRowKey);
        $('.rows_users').removeClass('rows_user_hover');
        $(this).addClass('rows_user_hover');
        $('.bar').addClass('hide');
        $(this).find('.bar').removeClass('hide');
        $('.list_row_users').jScrollPane({ animateScroll: true });

        $('.box_super_admin').addClass('hide');
        $('#view_super_admin').removeClass('hide');
        $('.btn_close').click(function (e) {
        $("#view_super_admin").addClass('hide');
        return false;
        });
        });*/

        $('.list_row_users').jScrollPane({ animateScroll: true });
    }
    // End Bind Data

    // Function Sort Admin
    function SortAdminFilter(str, index) {
        //$.fancybox.close();

        arrData = arrData.objSort(str, index);
        $(".list_row_users").find(".rows_users").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#rows_users_temp").clone();
            $(o).attr("id", arrData[i].id);
            if (i % 2 == 1) {
                $(o).addClass("users_alt");
            }
            $(o).removeClass("item_temp");
            $(o).find(".col_enterprise").html(arrData[i].enterprise);
            $(o).find(".col_brand").html(arrData[i].brand);
            $(o).find(".col_role").html(arrData[i].role);
            if (arrData[i].status == "true") {
                $(o).find(".col_status").html('Active');
            } else {
                $(o).find(".col_status").html('Inactive');
            }
            $(o).find(".colo_name").html(arrData[i].name);
            $(o).find(".colo_campaign").html(arrData[i].campaign);
            $(o).find(".colo_email").html(arrData[i].email);
            $(o).find(".col_username").html(arrData[i].username);
            $(o).find(".i_delete").attr('id', arrData[i].id);

            //            if (selectedRowKey == arrData[i].id.toString()) {
            //                $(o).addClass('rows_alert_hover');
            //                $(o).find('.bar').removeClass("hide");
            //            }

            if ($(".list_row_users").find(".jspPane").size() == 0) {
                $(".list_row_users").append(o);
            } else {
                $(".list_row_users").find(".jspPane").append(o);
            }
        }



        $('.rows_users').click(function () {

            selectedRowKey = $(this).attr("id");
            //alert(2);
            //alert(selectedRowKey);
            $('.rows_users').removeClass('rows_user_hover');
            $(this).addClass('rows_user_hover');
            $('.bar').addClass('hide');
            $(this).find('.bar').removeClass('hide');
            $('.list_row_users').jScrollPane({ animateScroll: true });

            //get Admin detail
            $.ajax({
                url: gb_servicePath + '/authenticateduser/ID/' + selectedRowKey + '.json',
                crossDomain: "true",
                type: "GET",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: "",
                dataType: 'json',
                success: function (data) {
                    if (data.StatusCode == 200) {
                        var admin = data.ReturnData;
                        var o = $('#view_super_admin');
                        $(o).find('#first_name_sum').html(admin.FirstName);
                        $(o).find('#last_name_sum').html(admin.LastName);
                        $(o).find('#email_sum').html(admin.EmailAddress);
                        $(o).find('#phone_sum').html(admin.PhoneNumber);
                        $(o).find('#username_sum').html(admin.UserName);
                        $(o).find('#timezone_sum').html(admin.TimeZoneID);
                        $('.list_camp_main').remove();
                        $.each(admin.CampaignRoleCountryInfo, function (i, val) {
                            var c = $(".list_camp_temp").clone();
                            $(c).removeClass("hide").removeClass('list_camp_temp').addClass('list_camp_main');
                            $(c).find(".td_campName").html(val.CampaignRoleInfo.CampaignInfo.Name);
                            $(c).find(".td_role").html(val.CampaignRoleInfo.RoleInfo.Name);
                            var countries = "";
                            $.each(val.CountryList, function (i, val_country) {
                                countries += val_country.Name + ", ";
                            });
                            $(c).find(".td_country").html(countries.substring(0, countries.length - 2));
                            $("#list_campign").append(c);

                        });
                    }
                },
                error: function (jqXHR, textStatus, xerror) {
                    if (isBug) {
                        alert("Error in /authenticateduser/ID/' + selectedRowKey + '.json ->" + xerror);
                    }
                }
            });
            $('.i_delete').click(function (e) {
                $("#box_confirm").modal({
                    opacity: 80,
                    overlayCss: { backgroundColor: "#000" }
                });

            });

            /*if (!$('#edit_super_admin').hasClass('hide')) {
            $('#view_super_admin').addClass('hide');
            return false;
            }*/
            $('.box_super_admin').addClass('hide');
            $('#view_super_admin').removeClass('hide');
            $('.btn_close').click(function (e) {
                $("#view_super_admin").addClass('hide');
                $('.rows_user_hover .bar').addClass('hide');
                $('.rows_users').removeClass('rows_user_hover');
                return false;
            });
        });

        $('.list_row_users').jScrollPane({ animateScroll: true });
    }
    // End Function Sort Admin
    function deleteUserAdmin(id) {

    }

    // Bind event click Sort By Enterprise
    $("#btSortEnterprise").find("img").css("visibility", "hidden");
    $("#btSortEnterprise").click(function () {
        SortAdminFilter("enterprise", -1 * parseInt($("#btSortEnterprise").attr("sort")));
        $("#btSortEnterprise").attr("sort", -1 * parseInt($("#btSortEnterprise").attr("sort")));

        $("#btSortEnterprise").find("img").css("visibility", "visible");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortEnterprise").attr("sort") == 1) {
            $("#btSortEnterprise").find("img").rotate(180);
        } else {
            $("#btSortEnterprise").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Enterprise
    // Bind event click Sort By Brand
    $("#btSortBrand").find("img").css("visibility", "hidden");
    $("#btSortBrand").click(function () {
        SortAdminFilter("brand", -1 * parseInt($("#btSortBrand").attr("sort")));
        $("#btSortBrand").attr("sort", -1 * parseInt($("#btSortBrand").attr("sort")));

        $("#btSortBrand").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortBrand").attr("sort") == 1) {
            $("#btSortBrand").find("img").rotate(180);
        } else {
            $("#btSortBrand").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Brand
    // Bind event click Sort By Role
    $("#btSortRole").find("img").css("visibility", "hidden");
    $("#btSortRole").click(function () {
        SortAdminFilter("role", -1 * parseInt($("#btSortRole").attr("sort")));
        $("#btSortRole").attr("sort", -1 * parseInt($("#btSortRole").attr("sort")));

        $("#btSortRole").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortRole").attr("sort") == 1) {
            $("#btSortRole").find("img").rotate(180);
        } else {
            $("#btSortRole").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Role
    // Bind event click Sort By Status
    $("#btSortStatus").find("img").css("visibility", "hidden");
    $("#btSortStatus").click(function () {
        SortAdminFilter("status", -1 * parseInt($("#btSortStatus").attr("sort")));
        $("#btSortStatus").attr("sort", -1 * parseInt($("#btSortStatus").attr("sort")));

        $("#btSortStatus").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortStatus").attr("sort") == 1) {
            $("#btSortStatus").find("img").rotate(180);
        } else {
            $("#btSortStatus").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Status    
    // Bind event click Sort By Name
    $("#btSortName").find("img").css("visibility", "hidden");
    $("#btSortName").click(function () {
        SortAdminFilter("name", -1 * parseInt($("#btSortName").attr("sort")));
        $("#btSortName").attr("sort", -1 * parseInt($("#btSortName").attr("sort")));

        $("#btSortName").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortName").attr("sort") == 1) {
            $("#btSortName").find("img").rotate(180);
        } else {
            $("#btSortName").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Name

    // Bind event click Sort By Campaign
    $("#btSortCampaign").find("img").css("visibility", "hidden");
    $("#btSortCampaign").click(function () {
        SortAdminFilter("campaign", -1 * parseInt($("#btSortCampaign").attr("sort")));
        $("#btSortCampaign").attr("sort", -1 * parseInt($("#btSortCampaign").attr("sort")));

        $("#btSortCampaign").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortCampaign").attr("sort") == 1) {
            $("#btSortCampaign").find("img").rotate(180);
        } else {
            $("#btSortCampaign").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Campaign

    // Bind event click Sort By Email
    $("#btSortEmail").find("img").css("visibility", "hidden");
    $("#btSortEmail").click(function () {
        SortAdminFilter("email", -1 * parseInt($("#btSortEmail").attr("sort")));
        $("#btSortEmail").attr("sort", -1 * parseInt($("#btSortEmail").attr("sort")));

        $("#btSortEmail").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortEmail").attr("sort") == 1) {
            $("#btSortEmail").find("img").rotate(180);
        } else {
            $("#btSortEmail").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Email
    // Bind event click Sort By Username
    $("#btSordUsername").find("img").css("visibility", "hidden");
    $("#btSordUsername").click(function () {
        SortAdminFilter("username", -1 * parseInt($("#btSordUsername").attr("sort")));
        $("#btSordUsername").attr("sort", -1 * parseInt($("#btSordUsername").attr("sort")));

        $("#btSordUsername").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");

        if ($("#btSordUsername").attr("sort") == 1) {
            $("#btSordUsername").find("img").rotate(180);
        } else {
            $("#btSordUsername").find("img").rotate(0);
        }
    });

    GetListAdmin();
    getListCampain(); //get all campaign
    getListCountries();
    //getListCountriesBoxLang();
    //getListCampainEdit();
    getListTimeZone();
    getListUser();
    getListMessagesType();
    $('#colorSelector').ColorPicker({
        color: '#0000ff',
        onShow: function (colpkr) {
            $(colpkr).show();
            $('.close_colorpicker').click(function () { $('.colorpicker').hide() });
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).hide();
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $('#colorSelector div').css('backgroundColor', '#' + hex);
            $('#txtcolor').val("#" + hex);
        }
    });
    $('.new_camp, #i_add_camp').click(function () {

        arrlanguage = new Array();

        $('#colorSelector').show();

        $('.country_box input, #txtcolor, #txtAudience, #txtAudience_desc').removeAttr('disabled', true);
        $('.age_allowed').attr('disabled', 'disabled')
        $("#new_campain h1.header_box_campain").html('New Campaign');

        setupLabel();
        // show color picker but position not done
        $('#colorSelector').bind('click', function () {
            $('.colorpicker').show();
            $('.close_colorpicker').click(function () { $('.colorpicker').hide() });
            return false;
        });
        //        $('#colorSelector').ColorPicker({
        //            color: '#0000ff',
        //            onShow: function (colpkr) {
        //                $(colpkr).show();
        //                $('.close_colorpicker').click(function () { $('.colorpicker').hide() });
        //                return false;
        //            },
        //            onHide: function (colpkr) {
        //                $(colpkr).hide();
        //                return false;
        //            },
        //            onChange: function (hsb, hex, rgb) {
        //                $('#colorSelector div').css('backgroundColor', '#' + hex);
        //                $('#txtcolor').val("#" + hex);
        //            }
        //        });
        $('.country_r input:text').val('');
        $('#txtCampName').val('');
        $('#txtCampDesc').val('');
        $('#txtcolor').val('');
        $('.colorSelector div').css('background-color', '');
        $('#txtAudience').val('');
        $('#txtAudience_desc').val('');
        $('.colorSelector div').css('background-color', '');
        $('#btnSaveCamp').addClass('new').removeClass('update'); ;
        $("#new_campain").modal();


        $('.list_key').jScrollPane({ animateScroll: true });
        $('.div_countries2').jScrollPane({ animateScroll: true });
        $('.list_count_main .case_main').click(function () {
            if ($(this).is(':checked')) {
                $(this).parent().parent().find('.age_allowed').removeAttr('disabled');
            }
            else {
                $(this).parent().parent().find('.age_allowed').attr('disabled', 'disabled');
            }
        });
        return false;
    });
    //setup label
    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });
    //Show make keyword box
    $('#btnAddNewLang').click(function (e) {
        $("#box_lang_popup").removeClass("hide");
        return false;
    });
    //    $('#lang_2').click(function (e) {
    //        $(".mk_kw_r").removeClass("hide");
    //    });
    $('#box_lang_popup_close, #box_keyword_popup_cancel').click(function (e) {
        $("#box_keyword_popup").addClass("hide");
    });

    //Show make country box
    $('#btnAddNewKey').click(function (e) {
        $("#box_lang_popup").removeClass("hide");
        getListCountriesBoxLang();
        return false;
    });
    $('#box_keyword_popup_close').click(function (e) {
        $("#box_lang_popup").addClass("hide");
    });
    function validateKeyword() {
        var flag = false;
        $('#box_keyword_popup .messagesflowtype .txta_camp_desc').each(function () {
            if ($(this).val() == "") {
                flag = true;
                return;
            }
        });
        if ($('#txt_key_in').val() == "" || $('#txt_key_out').val() == "" || flag) {
            $('#error_mess').css('display', 'block');
            $('#error_mess').html('Messages should be entered');
            return false;

        }
        return true;
    }
    $('#box_keyword_popup_save').click(function (e) {
        if (!validateKeyword()) return;
        $('#error_mess').css('display', 'none');
        var arr = $("#list_country input:checked").getCheckboxVal();
        var arrName = $("#list_country input:checked").getCheckboxName();

        var r = $("#rows_key_temp").clone();
        $(r).removeClass('hide').addClass('rows_key_mains');
        $(r).find(".col_lag").html($('#list_lang input[name=selection_lang]:checked').attr('id'));
        $(r).find(".col_lag").attr('lagID', $('#list_lang input[name=selection_lang]:checked').val());
        $(r).find(".col_k .key_button_mid2").html($('#txt_key_in').val());
        $(r).find(".col_k .key_button_mid2").attr('arr_key_in', JSON.stringify(buildKeyWorldCollection(6)));
        $(r).find(".col_f .key_button_mid2").html($('#txt_key_out').val());
        $(r).find(".col_f .key_button_mid2").attr('arr_key_out', JSON.stringify(buildKeyWorldCollection(7)));
        $(r).find(".col_coun").html(arrName.join(', '));
        $(r).find(".col_coun").attr('countryid', arr);
        $("#list_key_container").append(r);
        $('.rows_key_mains:odd').addClass('alt_row');
        $('.list_key').jScrollPane({ animateScroll: true });
        $("#box_keyword_popup").addClass("hide");

        //disable lang selected
        var objLang = new Object();
        objLang.lang = $("#list_lang").find('.r_on input:radio').attr('value');
        var arrcountry = new Array();
        var count = 0;
        $("#list_country .item_country").each(function () {
            count++;
        });
        $("#list_country .c_on").each(function () {
            arrcountry.push($(this).attr('id'));

        });
        objLang.countries = arrcountry;
        objLang.totalCountries = count;
        objLang.disable = false;
        addItemLanguage(objLang);
    });
    var arrlanguage = new Array();
    function addItemLanguage(obj) {
        for (var i = 0; i < arrlanguage.length; i++) {
            if (arrlanguage[i].lang == obj.lang) {
                arrlanguage[i].countries = arrlanguage[i].countries.concat(obj.countries);
                if (obj.totalCountries == arrlanguage[i].countries.length) {
                    arrlanguage[i].disable = true;
                }
                return true;
            }
        }
        if (obj.totalCountries == obj.countries.length) {
            obj.disable = true;
        }
        arrlanguage.push(obj);
        return false;
    }
    function resetFormKeyword() {
        $('#txt_key_in').val('');
        $('#txt_key_out').val('');
        $('#box_keyword_popup .txta_camp_desc').val('');
    }
    $('#box_keyword_popup_done').click(function (e) {
        resetFormKeyword();
        $("#box_lang_popup").addClass("hide");
        $("#box_keyword_popup").removeClass("hide");
    });

    $('.list_row_users').jScrollPane({ animateScroll: true });
    $('body').addClass('has-js');
    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });
    setupLabel();

    $('.rows_users').click(function () {

        //selectedRowKey = $(this).attr("id");
        $('.rows_users').removeClass('rows_user_hover');
        $(this).addClass('rows_user_hover');
        $('.bar').addClass('hide');
        $(this).find('.bar').removeClass('hide');
        $('.list_row_users').jScrollPane({ animateScroll: true });

        $('.box_super_admin').addClass('hide');
        $('#view_super_admin').removeClass('hide');

        $('.btn_close').click(function (e) {
            $("#view_super_admin").addClass('hide');
            return false;
        });

        $('.i_delete').click(function (e) {
            $("#box_confirm").modal({
                opacity: 80,
                overlayCss: { backgroundColor: "#000" }
            });
            return false;
        });

        //                $('#box_confirm').jqm();
        //                $('#box_confirm').jqmAddClose($('.btn_Cancel'));
        //                $('#box_confirm').jqmAddClose($('.btn_OK'));

    });
    // Get Function Get List Countries and Language
    function getListCountriesToCampaign(arrCountries) {
        //alert(arrCountries.toSource());
        $("#rows_key_template").css("display", "none");
        $("#profile_country_template").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {

                        var langobj;
                        var arrLang = new Array();
                        $.each(json1.ReturnData, function (i, val) {
                            // check if alredy add country in combobox
                            //if ($("#country" + val.Country.Id).length == 0) {
                            var o = $("#profile_country_template").clone();
                            $(o).css("display", "block");
                            if (i % 2) {
                                $(o).addClass("alt_row");
                            }
                            $(o).addClass("list_count_main2");
                            $(o).find("input.case").attr("value", val.Country.Name);
                            $(o).find("input.case").attr("name", val.Country.Id);
                            $(o).find("input.case").addClass("case_main");
                            $(o).attr("id", "country" + val.Country.Id);
                            $(o).attr("value", val.Country.Id);
                            $(o).find("span").html(val.Country.Name);
                            $(o).find("div.country_c").attr("id", "country_c_" + val.Country.Id);
                            $(o).find("div.country_r").attr("id", "country_r_" + val.Country.Id);
                            $(".div_countries2").removeClass('hide');
                            $(".div_countries2").append(o);

                            langobj = new Object();
                            langobj.Id = val.Language.Id;
                            langobj.Name = val.Language.Name;
                            langobj.Countries = val.Country.Name;
                            if (i == 0) {
                                arrLang.push(langobj);
                            }
                            else {
                                for (var k = 0; k < arrLang.length; k++) {
                                    if (arrLang[k].Name == langobj.Name) {
                                        arrLang[k].Countries = arrLang[k].Countries + ", " + langobj.Countries;
                                    }
                                    else {
                                        arrLang.push(langobj);
                                    }
                                }
                            }
                        });
                        for (var j = 0; j < arrLang.length; j++) {
                            var b = $("#rows_key_template").clone();
                            $(b).css("display", "block");
                            if (j % 2) {
                                $(b).addClass("alt_row");
                            }
                            $(b).attr('id', arrLang[j].Id);
                            $(b).find('.col_lag').html(arrLang[j].Name);
                            $(b).find('.col_coun').html(arrLang[j].Countries);
                            $(".list_key #list_container").append(b);
                        }
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            if ($("#new_campain h1.header_box_campain").html() != 'Edit Campaign') {
                                setupLabel();
                            }
                        });
                        //$('.div_countries2').jScrollPane();
                        $('.list_key').jScrollPane({ animateScroll: true });
                        $('.div_countries2').jScrollPane({ animateScroll: true });
                    }
                });
        for (var j = 0; j < arrCountries.length; j++) {

            //                    if (parseInt(arrCountries[j].Id, '10') == parseInt(val.Country.Id, '10')) {
            //                        alert(arrCountries[j].Id);
            //                        $(o).find(".country_l").addClass('c_on');
            //                    }
            //alert(arrCountries[j].Id);
            $('.div_countries2 #rows_country' + arrCountries[j].Countryid).find('.country_l').addClass('c_on');
            $('.div_countries2 #rows_country' + arrCountries[j].Countryid).find('.country_r input').val(arrCountries[j].ValidAge);
            if (arrCountries[j].ValidAge > 0) {
                $('.div_countries2 #rows_country' + arrCountries[j].Countryid).find('.country_c').addClass('c_on');
                $('.div_countries2 #rows_country' + arrCountries[j].Countryid).find('.country_c .label_check').addClass('c_on');
            }
            //$('.div_countries2 #country' + arrCountries[j].Id).find('.country_l').addClass('c_on');
        }
    }

    function GetCampaignById(id) {
        $.getJSON(gb_servicePath + '/campaign/ID/' + id + '.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        var data = json1.ReturnData;
                        if (data == null) {

                            alert("Wrong Campaign id");

                            return;
                        }
                        //                        var arrCountries = data.Countrys;
                        //                        getListCountriesToCampaign(arrCountries); // add list Countries
                        //                        $("#new_campain h1.header_box_campain").html('Edit Campaign');
                        //                        $('#txtCampName').val(data.Name);
                        //                        $('#txtCampName').attr('campID', id);
                        //                        $('#txtCampDesc').val(data.Desc);
                        //                        $('#txtcolor').val(data.ColorCode);
                        //                        $('.colorSelector div').css('background-color', data.ColorCode);
                        //                        $('#txtAudience').val(data.CampaignAudience.Name);
                        //                        $('#txtAudience_desc').val(data.CampaignAudience.Desc);
                        //                        $('.colorSelector div').css('background-color', data.ColorCode);
                        //                        $('#btnSaveCamp').addClass('update').removeClass('new');
                        //                        $("#new_campain").modal();

                        var arrCountries = data.Countrynumbermappings;
                        setupLabel();
                        $('.age_allowed').val('');
                        getListCountriesToCampaign(arrCountries); // add list Countries
                        $("#new_campain h1.header_box_campain").html('Edit Campaign');
                        $('#txtCampName').val(data.Name);
                        $('#txtCampName').attr('campID', id);
                        $('#txtCampDesc').val(data.Desc);
                        $('#txtcolor').val(data.ColorCode);
                        $('.colorSelector div').css('background-color', data.ColorCode);
                        $('#txtAudience').val(data.CampaignAudience.Name);
                        $('#txtAudience_desc').val(data.CampaignAudience.Desc);
                        $('.colorSelector div').css('background-color', data.ColorCode);
                        $('#btnSaveCamp').addClass('update').removeClass('new');

                        $('.list_key .rows_key_mains').remove();


                        var arrayKeywords = new Array();
                        arrayKeywords = data.CommonKeywords;
                        for (var j = 0; j < arrayKeywords.length; j++) {
                            if (j % 2 == 0) {
                                var str = '';
                                var idstr = '';
                                //var r2 = '';
                                var r = $("#rows_key_temp").clone();
                                $(r).removeClass('hide').addClass('rows_key_mains');
                                $(r).find(".col_lag").html(arrayKeywords[j].Language.Name);
                                $(r).find(".col_lag").attr('lagID', arrayKeywords[j].Language.Id);

                                if (arrayKeywords[j].ComponentName == 'Opt In') {
                                    $(r).find(".col_k .key_button_mid2").html(arrayKeywords[j].Name);
                                    $(r).find(".col_k .key_button_mid2").attr('arr_key_in', arrayKeywords[j].Name);
                                }
                                else {
                                    $(r).find(".col_f .key_button_mid2").html(arrayKeywords[j].Name);
                                    $(r).find(".col_f .key_button_mid2").attr('arr_key_out', arrayKeywords[j].Name);
                                }
                                str = arrayKeywords[j].Country.Name;
                                idstr = arrayKeywords[j].Country.Id;
                                if (arrayKeywords.length > (j + 1)) {
                                    if (arrayKeywords[j].ComponentName != arrayKeywords[j + 1].ComponentName) {
                                        if (arrayKeywords[j + 1].ComponentName == 'Opt In') {
                                            $(r).find(".col_k .key_button_mid2").html(arrayKeywords[j + 1].Name);
                                            $(r).find(".col_k .key_button_mid2").attr('arr_key_in', arrayKeywords[j + 1].Name);
                                        }
                                        else {
                                            $(r).find(".col_f .key_button_mid2").html(arrayKeywords[j + 1].Name);
                                            $(r).find(".col_f .key_button_mid2").attr('arr_key_out', arrayKeywords[j + 1].Name);
                                        }
                                    }
                                    //                                    else {
                                    //                                        r2 = $("#rows_key_temp").clone();
                                    //                                        $(r2).removeClass('hide').addClass('rows_key_mains');
                                    //                                        $(r2).find(".col_lag").html(arrayKeywords[j+1].Language.Name);
                                    //                                        $(r2).find(".col_lag").attr('lagID', arrayKeywords[j+1].Language.Id);
                                    //                                    }
                                    if (arrayKeywords[j].Country.Name != arrayKeywords[j + 1].Country.Name) {
                                        str = str + ', ' + arrayKeywords[j + 1].Country.Name;
                                        idstr = idstr + ', ' + arrayKeywords[j + 1].Country.Id;
                                    }
                                }
                                else {
                                    $(r).find(".col_f .key_button_mid2").html('');
                                    $(r).find(".col_f .key_button_mid2").attr('arr_key_out', '');
                                }
                                $(r).find(".col_coun").html(str);
                                $(r).find(".col_coun").attr('countryid', idstr);
                                $("#list_key_container").append(r);
                                $('.rows_key_mains:odd').addClass('alt_row');
                            }
                        }
                        $('.list_key').jScrollPane({ animateScroll: true });
                        $("#new_campain").modal();


                    }
                });
    }
    $('.edit_camp').click(function (e) {
        //campaign/ID/<id>.json
        var id = $('#cb_camp').children(":selected").attr("name");
        //        var selected = new Array();
        //        $('.list_campaign_cb input.case_campaign[type=checkbox]:checked').each(function () {
        //            //var sThisVal = (this.checked ? $(this).val() : "");
        //            selected.push($(this).attr("name"));
        //        });
        if (id == 0) {

            alert('Please select a campaign');

            return false;
        }
        else {
            $('#colorSelector').hide();
            $('.country_box input, #txtcolor, #txtAudience, #txtAudience_desc').attr('disabled', true);
            GetCampaignById(id);
            $('.list_key').jScrollPane({ animateScroll: true });
            $('.div_countries2').jScrollPane({ animateScroll: true });
            return false;
        }
    });
    $('.edit_camp2').click(function (e) {
        //campaign/ID/<id>.json
        var id = $('#cb_edit_camp').children(":selected").attr("name");

        //        var selected = new Array();
        //        $('.list_campaign_cb_edit input.case_campaign_edit[type=checkbox]:checked').each(function () {
        //            //var sThisVal = (this.checked ? $(this).val() : "");
        //            selected.push($(this).attr("name"));
        //        });
        if (id == 0) {

            alert('Please select a campaign');

            return false;
        }
        //        else if (selected.length > 1) {

        //            alert('Please select a campaign');

        //            return false;
        //        }
        else {
            $('#colorSelector').unbind('click');
            $('.country_box input, #txtcolor, #txtAudience, #txtAudience_desc').attr('disabled', true);
            GetCampaignById(id);
            $('.list_key').jScrollPane({ animateScroll: true });
            $('.div_countries2').jScrollPane({ animateScroll: true });
            return false;
        }
    });
    $('select.select_short4').customStyle();
    $('select.select_time').customStyle();

    // Custom drop down list Campaign
    //    $("#checkallCampaign").click(function () {
    //        $('.case_campaign.case_main').attr('checked', 'checked');
    //        setupLabel();
    //    });
    //    $("#clearallCampaign").click(function () {
    //        $('.case_campaign.case_main').removeAttr('checked');
    //        setupLabel();
    //    });
    //    $('.campaign').hide();
    //    $('.btn_campaign').click(function (event) {
    //        event.stopPropagation();
    //        if ($('.campaign').css('display') == 'none') {
    //            $('.campaign').show();
    //            // scrollpane not apply when displaynone
    //            $('.list_campaign_cb').jScrollPane();
    //        } else {
    //            $('.campaign').hide();
    //        }
    //        $(document).click(function () {
    //            if ($('.campaign').css('display') != 'none') {
    //                $('.campaign').hide();
    //            }
    //        });
    //        $('.campaign').click(function (event) {
    //            event.stopPropagation();
    //        });
    //    });
    // End Custom drop down list Campaign

    // Custom drop down list Campaign edit
    //    $("#checkallCampaign_edit").click(function () {
    //        $('.case_campaign_edit.case_main').attr('checked', 'checked');
    //        setupLabel();
    //    });
    //    $("#clearallCampaign_edit").click(function () {
    //        $('.case_campaign_edit.case_main').removeAttr('checked');
    //        setupLabel();
    //    });
    //    $('.campaign_edit').hide();
    //    $('.btn_campaign_edit').click(function (event) {
    //        event.stopPropagation();
    //        if ($('.campaign_edit').css('display') == 'none') {
    //            $('.campaign_edit').show();
    //            // scrollpane not apply when displaynone
    //            $('.list_campaign_cb_edit').jScrollPane();
    //        } else {
    //            $('.campaign_edit').hide();
    //        }
    //        $(document).click(function () {
    //            if ($('.campaign_edit').css('display') != 'none') {
    //                $('.campaign_edit').hide();
    //            }
    //        });
    //        $('.campaign_edit').click(function (event) {
    //            event.stopPropagation();
    //        });
    //    });
    // End Custom drop down list Campaign edit

    //build Campaign object
    function buildCampaignCollection() {
        var campaign = new Object();
        campaign.name = $('#txtEditCampName').val();
        campaign.validage = "";

        campaign.description = "";
        campaign.colorcode = "";

        var brandids = new Array();
        brandids.push("1");
        campaign.brandids = brandids;

        var keywordids = new Array();
        keywordids.push("1");
        campaign.keywordids = keywordids;

        var countryids = new Array();
        countryids.push("5");
        campaign.countryids = countryids;

        return campaign;
    }

    // Function Get List Campain
    //  function getListCampain() {
    //        $("#listCampainTemplate").css("display", "none");
    //        $('.list_campaign_cb .list_count').remove();
    //        $.getJSON(gb_servicePath + '/campaign/list/summary.json',
    //                function (json1) {
    //                    if (json1.StatusCode == 200) {
    //                        $.each(json1.ReturnData, function (i, val) {
    //                            $('.list_campaign_cb').jScrollPane();
    //                            var o = $("#listCampainTemplate").clone();
    //                            $(o).css("display", "block");
    //                            $(o).find("input").attr("value", val.Name);
    //                            $(o).find("input").attr("name", val.Id);
    //                            $(o).find("input").addClass("case_main");
    //                            $(o).attr("id", val.Id);
    //                            $(o).find("span").html(val.Name);
    //                            $(".list_campaign_cb .jspPane").append(o);
    //                        });
    //                        $('.label_check, .label_radio, .label_check_ip').click(function () {
    //                            setupLabel();
    //                        });
    //                    }
    //                    //getListCountries();
    //                });
    //  }
    // End Function Get List Campain

    // Function Get List Campain Edit
    //    function getListCampainEdit() {
    //        $("#listCampainTemplate_edit").css("display", "none");
    //        $('.list_campaign_cb_edit .list_count').remove();
    //        $.getJSON(gb_servicePath + '/campaign/list/summary.json',
    //                function (json1) {
    //                    if (json1.StatusCode == 200) {
    //                        $.each(json1.ReturnData, function (i, val) {
    //                            $('.list_campaign_cb_edit').jScrollPane();
    //                            var o = $("#listCampainTemplate_edit").clone();
    //                            $(o).css("display", "block");
    //                            $(o).find("input").attr("value", val.Name);
    //                            $(o).find("input").attr("name", val.Id);
    //                            $(o).find("input").addClass("case_main");
    //                            $(o).attr("id", val.Id);
    //                            $(o).find("span").html(val.Name);
    //                            $(".list_campaign_cb_edit .jspPane").append(o);
    //                        });
    //                        $('.label_check, .label_radio, .label_check_ip').click(function () {
    //                            setupLabel();
    //                        });
    //                    }
    //                    //getListCountries();
    //                });
    //    }
    // End Function Get List Campain

    // Get Function Get List Countries
    function getListCountries() {
        $("#listCountriesTemplate").css("display", "none");
        $("#profile_country_template").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        var strLangIdAdded = "";
                        var langId;
                        $.each(json1.ReturnData, function (i, val) {
                            if ($("#rows_country" + val.Country.Id).length == 0) {
                                // check if alredy add country in combobox
                                //if ($("#country" + val.Country.Id).length == 0) {                            
                                var o = $("#profile_country_template").clone();
                                $(o).css("display", "block");
                                if (i % 2) {
                                    $(o).addClass("alt_row");
                                }
                                $(o).addClass("list_count_main");
                                $(o).find("input.case").attr("value", val.Country.Name);
                                $(o).find("input.case").attr("name", val.Country.Id);
                                $(o).find("input.case").addClass("case_main");
                                $(o).attr("id", "rows_country" + val.Country.Id);
                                $(o).find("label.country_l").attr("id", val.Country.Id);
                                $(o).attr("value", val.Country.Id);
                                $(o).find("span").html(val.Country.Name);
                                $(o).find("div.country_c").attr("id", "country_c_" + val.Country.Id);
                                $(o).find("div.country_r").attr("id", "country_r_" + val.Country.Id);
                                $(".div_countries2").append(o);
                            }
                            if ($(".div_countries #country" + val.Country.Id).length == 0) {
                                var oo = $("#listCountriesTemplate").clone();
                                $(oo).css("display", "block");
                                $(oo).find("input").attr("value", val.Country.Name);
                                $(oo).find("input").attr("name", val.Country.Id);
                                $(oo).find("input").addClass("case_main");
                                $(oo).attr("id", "country" + val.Country.Id);
                                $(oo).attr("value", val.Country.Id);
                                $(oo).find("span").html(val.Country.Name);
                                $(".div_countries").append(oo);
                            }
                            //}

                        });
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            if ($("#new_campain h1.header_box_campain").html() != 'Edit Campaign') {
                                setupLabel();
                            }
                        });
                        $('.div_countries').jScrollPane();
                        $('.div_countries2').jScrollPane();
                    }
                });
    }
    // End Get Function Get List Countries

    function checkMail() {
        var mail = $('#txtEmail').val();
        var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (mail == '') {
            $('#email').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            return false;
        }
        else if (emailReg.test(mail)) {
            // TODO: email is true
            $('#email').css('color', '#6D6D6D');
            return true;
        }
        else {
            $('#email').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Email address not on file');
            $('#warning').css('color', '#ff5050');
            return false;
        } //Please complete required fields
    }
    function checkEmpty() {
        var co = true;

        var valEmp = $('#sltRole option:selected').text();
        var fisrt = $('#txtFirstName').val();
        var last = $('#txtLastName').val();
        var mail = $('#txtEmail').val();
        var phone = $('#txtPhone').val();
        var selected = new Array();
        $('#countries3').css('color', '#6D6D6D');

        $('input.case[type=checkbox]:checked').each(function () {
            //var sThisVal = (this.checked ? $(this).val() : "");
            selected.push($(this).val());
        });

        //        if (selected.length == 0) {
        //            $('#countries3').css('color', '#ff5050');
        //            $('#warning').html('Please complete required fields');
        //            $('#warning').css('color', '#ff5050');
        //        }
        if (valEmp == 'Select Role') {
            $('#role').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (phone == '') {
            $('#phone').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (mail == '') {
            $('#email').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (last == '') {
            $('#lastname').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (fisrt == '') {
            $('#firstname').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        return co;
    }
    $('#btnEdit').click(function () {
        if (!checkEmpty()) {
            return false;
        }
        else if (!checkMail()) {
            return false;
        }
        var authUser = buildAccount();
        $.ajax({
            url: gb_servicePath + "/authenticateduser/update/" + $('.rows_user_hover').attr("id") + ".json",
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(authUser),
            "dataType": 'json',
            success: function (data) {
                $('#edit_super_admin').addClass('hide');
                resetForm();
                $(".list_row_users").find("img").show();
                $(".list_row_users .rows_users").hide();
                GetListAdmin();
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error");
                    alert(authUser);
                }
            }

        });
    });

    function getListMessagesType() {
        $.getJSON(gb_servicePath + '/component/list.json?productname=Common',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (val.Id == 6 || val.Id == 7) {
                                for (var i = 0; i < val.MessageflowType.length; i++) {
                                    var o = $(".message_optin_temp").clone();
                                    $(o).removeClass('hide').removeClass('message_optin_temp');
                                    $(o).attr("id", "messagestype" + val.MessageflowType[i].Id);
                                    $(o).attr("value", val.MessageflowType[i].Id);
                                    $(o).addClass("messagesflowtype");
                                    $(o).css("display", "block");
                                    $(o).find("b").html("Message for Message Type: " + val.MessageflowType[i].Name);
                                    if (val.Id == 6) {
                                        $("#list_mess_optin").append(o);
                                    }
                                    if (val.Id == 7) {
                                        $("#list_mess_optout").append(o);
                                    }
                                }
                            }
                        });
                    }
                });
    }

    //Campaign
    function checkEmptyCamp() {
        var co = true;
        var name = $('#txtCampName').val();
        var desc = $('#txtCampDesc').val();
        var audience_name = $('#txtAudience').val();
        var audience_desc = $('#txtAudience_desc').val();
        var selected = new Array();
        $('#countries').css('color', '#6D6D6D');

        $('input.case[type=checkbox]:checked').each(function () {
            //var sThisVal = (this.checked ? $(this).val() : "");
            selected.push($(this).val());
        });
        if (audience_desc == '') {
            $('#audience_desc').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (audience_name == '') {
            $('#audience_name').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        //        if (selected.length == 0) {
        //            $('#countries').css('color', '#ff5050');
        //            $('#warning2').html('Please complete required fields');
        //            $('#warning2').css('color', '#ff5050');
        //        }
        if (name == '') {
            $('#campname').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (desc == '') {
            $('#campdesc').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        return co;
    }

    function buildKeyWorldCollection(compId) {
        var keyword = new Object();
        if (compId == 6) {
            keyword.name = $("#txt_key_in").val();
        } else {
            keyword.name = $("#txt_key_out").val();
        };

        keyword.componentid = compId; // Here function is component for alert/Hub
        //var audience = new Array();
        //audience.push($("#audience_selection").find("option:selected").attr("id"));
        //keyword.grouplist = audience;
        //keyword.campaignid = ""; //campaign id is the same as the campaign id of the alert collection
        //        var arrCountryId = $("#make_keyword_alert").attr("messflowid").split("_");
        //        keyword.countryid = arrCountryId[0];  //countryid is the same as it’s parent message flow
        //        keyword.languageid = arrCountryId[1]; //languageid is the same as it’s parent message flow
        //        keyword.mediaid = arrCountryId[2]; //media is the same as it’s parent message flow 
        var messagelist = new Array();
        if (compId == 6) {
            $("#list_mess_optin").find(".messagesflowtype").each(function () {
                if ($(this).find(".txta_camp_desc").val() != "") {
                    var message1 = new Object();
                    message1.messageflowtypeid = $(this).attr("value"); // message type id
                    message1.messagebody = $(this).find(".txta_camp_desc").val(); // message body
                    messagelist.push(message1); //add message1 to keyword object    
                }
            });
        }
        if (compId == 7) {
            $("#list_mess_optout").find(".messagesflowtype").each(function () {
                if ($(this).find(".txta_camp_desc").val() != "") {
                    var message1 = new Object();
                    message1.messageflowtypeid = $(this).attr("value"); // message type id
                    message1.messagebody = $(this).find(".txta_camp_desc").val(); // message body
                    messagelist.push(message1); //add message1 to keyword object    
                }
            });
        }
        keyword.messagelist = messagelist;
        return keyword;
    }
    function makeKeyword(campId, audienceId, countryId, languageId, dataIn, dataOut) {
        var campaign = buildCampaign();
        var keywordids = [];

        var arrKeyIn = jQuery.parseJSON(dataIn);
        //alert(arrKeyIn);
        var audience = new Array();
        audience.push(audienceId.toString());

        arrKeyIn.grouplist = audience;
        arrKeyIn.campaignid = campId.toString(); //campaign id is the same as the campaign id of the alert collection
        arrKeyIn.countryid = countryId
        arrKeyIn.languageid = languageId
        arrKeyIn.mediaid = "1";

        var arrKeyOut = jQuery.parseJSON(dataOut);
        //alert(arrKeyOut);
        arrKeyOut.grouplist = audience;
        arrKeyOut.campaignid = campId; //campaign id is the same as the campaign id of the alert collection
        arrKeyOut.countryid = countryId;
        arrKeyOut.languageid = languageId;
        arrKeyOut.mediaid = "1";
        $.ajax({
            url: gb_servicePath + "/keyword/create.json",
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(arrKeyIn),
            "dataType": 'json',
            async: false,
            success: function (data) {
                keywordids.push(data.ReturnData.Id);
                //alert(data.ReturnData.Id);
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/keyword/create.json");
                }
            }
        });
        $.ajax({
            url: gb_servicePath + "/keyword/create.json",
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(arrKeyOut),
            "dataType": 'json',
            async: false,
            success: function (data) {
                keywordids.push(data.ReturnData.Id);
                //alert('ok');
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/keyword/create.json");
                }
            }
        });
        campaign.keywordids = keywordids;
        $.ajax({
            url: gb_servicePath + "campaign/update/" + campId + ".json",
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(campaign),
            "dataType": 'json',
            success: function (data) {
                //window.location.href = '../profile/SuperAdminDash';
                //window.location.href = '../profile/SuperAdminDash';
                getListCampain(); //get all campaign
                $.modal.close();
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in GEMAPI/campaign/update.json");
                }
            }

        });

    }
    $('#btnSaveCamp').click(function () {
        if (!checkEmptyCamp()) {
            return false;
        } else {
            var campaign = buildCampaign();
            var url;
            if ($(this).hasClass('update')) {
                url = "campaign/update/" + $("#txtCampName").attr("campID") + ".json";
            }
            if ($(this).hasClass('new')) {
                url = "/campaign/create.json";
            }
            $.ajax({
                url: gb_servicePath + url,
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(campaign),
                "dataType": 'json',
                success: function (data) {
                    var dataCampaign = data.ReturnData;
                    $('.rows_key_mains').each(function () {
                        //alert($(this).find('.col_k .key_button_mid2').attr('arr_key_in'));
                        makeKeyword(dataCampaign.Id, dataCampaign.CampaignAudience.ID, $(this).find('.col_coun').attr('countryid'), $(this).find('.col_lag').attr('lagid'), $(this).find('.col_k .key_button_mid2').attr('arr_key_in'), $(this).find('.col_f .key_button_mid2').attr('arr_key_out'));
                    });
                },
                error: function (jqXHR, textStatus) {
                    if (isBug) {
                        alert("Error in GEMAPI/campaign/create.json");
                    }
                }

            });
            return true;
        }
    });

    //Build Account to POST
    function buildAccount() {
        var authUser = new Object();

        authUser.email = $('#txtEmail').val();
        authUser.phonenumber = $('#txtPhone').val();
        authUser.timezone = $("#timezone_selection").find("option:selected").attr("name");
        authUser.userrole = $("#sltRole").find("option:selected").attr("name"); // the role of user to be created
        authUser.userid = userId;

        //SoliAdmin=1,
        //SuperAdmin=2,
        //Admin=3,
        //User=4,
        //Unknown=5
        //for admin and common users only
        var campaigncountry = new Object();
        campaigncountry.campaignid = $('#cb_edit_camp').children(":selected").attr("name");

        var countryids = new Array();
        var arrName = $(".for_edit input:checked").getCheckboxName();
        countryids.splice(0, countryids.length);
        //campaign to filter
        for (i = 0; i < arrName.length; i++) {
            countryids.push(arrName[i]);
        }
        campaigncountry.countryids = countryids;
        authUser.campaigncountrymapping = campaigncountry;

        //        var countryids = new Array();
        //        countryids.push("1");
        //        campaigncountry.countryids = countryids;
        //        authUser.campaigncountrymapping = campaigncountry;

        //for super admin users only

        authUser.brandid = "1";
        return authUser;
    }

    // Update new account
    $('#btn_update_new_acc').click(function () {
        if ($("#cb_user option:selected").attr('name') != 0 && $("#ddl_user_new option:selected").attr('name') != 0) {
            $("#select_user_lbl").css('color', '#595959');
            $("#role_label").css('color', '#595959');

            var authUser = new Object();

            authUser.firstname = $('#first_name_sum_new').html();
            authUser.lastname = $('#last_name_sum_new').html();
            authUser.email = $('#email_sum_new').html();
            authUser.phonenumber = $('#phone_sum_new').html();
            authUser.timezone = $("#timezone_sum_new").html();
            authUser.userid = userId;
            authUser.userrole = $("#ddl_user_new option:selected").attr('name'); // the role of user to be created
            //SoliAdmin=1,
            //SuperAdmin=2,
            //Admin=3,
            //User=4,
            //Unknown=5
            //for admin and common users only
            var campaigncountry = new Object();
            campaigncountry.campaignid = $('#cb_camp').children(":selected").attr("name");

            var countryids = new Array();
            var arrName = $(".for_new input:checked").getCheckboxName();
            countryids.splice(0, countryids.length);
            //campaign to filter
            for (i = 0; i < arrName.length; i++) {
                countryids.push(arrName[i]);
            }
            campaigncountry.countryids = countryids;
            authUser.campaigncountrymapping = campaigncountry;

            //            var countryids = new Array();
            //            countryids.push("1");
            //            campaigncountry.countryids = countryids;
            //            authUser.campaigncountrymapping = campaigncountry;

            $.ajax({
                url: gb_servicePath + "/authenticateduser/update/" + $("#cb_user option:selected").attr('name') + ".json",
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(authUser),
                "dataType": 'json',
                success: function (data) {
                    $('#new_super_admin').addClass('hide');
                    resetForm();
                    $(".list_row_users").find("img").show();
                    $(".list_row_users .rows_users").hide();
                    GetListAdmin();
                },
                error: function (jqXHR, textStatus) {
                    if (isBug) {
                        alert("Error");
                        alert(authUser);
                    }
                }

            });
        } else {
            // Validate select user
            // Show red label
            if ($("#cb_user option:selected").attr('name') == 0) {
                $("#select_user_lbl").addClass('red');
                return;
            } else {
                $("#select_user_lbl").removeClass('red');
            }
            // Validate selecte role
            // Show red label            
            if ($("#ddl_user_new option:selected").attr('name') == 0) {
                $("#role_label").addClass('red');
                return;
            } else {
                $("#role_label").removeClass('red');
            }

        }
    });
    // Vilidate data when add new user account
    $('#btn_create_new_acc').click(function () {
        if (!checkEmty2()) {
            $('#lblRequired_1').addClass('red');
            $('#lblRequired_1').html('Please complele required fields');
            return false;
        }
        else {
            if (!checkMail2()) {
                return false;
            }
            else {
                var authUser = new Object();

                authUser.firstname = $('#first_name_user').val();
                authUser.lastname = $('#last_name_user').val();
                authUser.email = $('#email_user').val();
                authUser.phonenumber = $('#phone_user').val();
                authUser.timezone = $("#timezone_selection_new").find("option:selected").attr("name");

                authUser.userrole = $("#ddl_user_new option:selected").attr("name");
                //SoliAdmin=1,
                //SuperAdmin=2,
                //Admin=3,
                //User=4,
                //Unknown=5
                //for admin and common users only
                var campaigncountry = new Object();
                campaigncountry.campaignid = $('#cb_camp').children(":selected").attr("name");
                var countryids = new Array();
                var arrName = $(".for_new input:checked").getCheckboxName();
                countryids.splice(0, countryids.length);
                //campaign to filter
                for (i = 0; i < arrName.length; i++) {
                    countryids.push(arrName[i]);
                }
                campaigncountry.countryids = countryids;
                authUser.campaigncountrymapping = campaigncountry;

                //for super admin users only

                authUser.brandid = "1";

                $.ajax({
                    url: gb_servicePath + "/authenticateduser/create.json",
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(authUser),
                    "dataType": 'json',
                    success: function (data) {
                        $('#new_super_admin').addClass('hide');
                        resetForm();
                        $(".list_row_users").find("img").show();
                        $(".list_row_users .rows_users").hide();
                        GetListAdmin();
                    },
                    error: function (jqXHR, textStatus) {
                        if (isBug) {
                            alert("Error");
                            alert(authUser);
                        }
                    }

                });
            }
        }

    });

    $('#first_name_user').keypress(function () {
        $('#first_name_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#last_name_user').keypress(function () {
        $('#last_name_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#email_user').keypress(function () {
        $('#email_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#phone_user').keypress(function () {
        $('#phone_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#timeZone_user').change(function () {
        $('#timeZone_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#role_user').change(function () {
        $('#role_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });
    $('#countries_user .label_check').click(function () {
        $('#countries_label').removeClass('red');
        $('#lblRequired_1').removeClass('red');
        $('#lblRequired_1').html('Required fields');
    });

});
//Campaign Collection
function buildCampaign() {
    var campaign = new Object();  

    campaign.name = $("#txtCampName").val();
    campaign.description = $("#txtCampDesc").val();
    campaign.colorcode = $("#txtcolor").val();

    var brandids = new Array();
    brandids.push("1");
    campaign.brandids = brandids;

    // Pass null to keyword
    var keywordids = new Array();
    //keywordids.push("1");
    campaign.keywordids = keywordids;

    var countrynumbermappings = new Array();
//    countrynumbermapping.countryid = "1";
    //    countrynumbermapping.validationage = "16";
    $(".list_count_main").each(function (val, i) {
        if ($(this).find('input.case_main').is(':checked')) {
            var countrynumbermapping = new Object();
            countrynumbermapping.countryid = $(this).find('.country_l.c_on').attr('id');
            countrynumbermapping.validationage = $(this).find('input.age_allowed').val();
            countrynumbermappings.push(countrynumbermapping);
        }
    });
    campaign.countrynumbermapping = countrynumbermappings;

    var audience = new Object();
    audience.name = $('#txtAudience').val();
    audience.description = $('#txtAudience_desc').val();
    audience.audiencelevel = "1";

    if ($('#btnSaveCamp').hasClass('update')) {
        audience.campaignid = $("#txtCampName").attr('campID');
    }
    //  1 -> Campaign Level, for audience create along with Campaign

    //  2 -> Sub Group Level, for all other cases in V1


    campaign.audience = audience;
    campaign.userid = userId;

    return campaign;
}

function showEdit() {
    $('.box_super_admin').addClass('hide');
    $('#edit_super_admin').removeClass('hide');
    $('.div_countries').jScrollPane({ animateScroll: true });
    selectedRowKey = $('.rows_user_hover').attr("id");
    $.ajax({
        url: gb_servicePath + '/authenticateduser/ID/' + selectedRowKey + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var admin = data.ReturnData;
                $('#txtFirstName').val(admin.FirstName);
                $('#txtLastName').val(admin.LastName);
                $('#txtEmail').val(admin.EmailAddress);
                $('#txtPhone').val(admin.PhoneNumber);
                $('.tr_username').removeClass('hide');
                $('#lbl_username').html(admin.UserName);
                $('#cb_timezone option[name=' + admin.TimeZoneID + ']').attr("selected", "selected");
                $('#timezone_selection .customStyleSelectBoxInner').html($('#cb_timezone option[name=' + admin.TimeZoneID + ']').val());
                $('#sltRole option[name=' + admin.UserRoles[0].RoleType + ']').attr("selected", "selected");
                $('.sltRole .customStyleSelectBoxInner').html($('#ddl_user_new option[name=' + admin.UserRoles[0].RoleType + ']').val());

                $('.for_edit .label_check').removeClass('c_on');
                $('.for_edit .list_count input').attr('checked', false);
                if (admin.CampaignRoleCountryInfo != "") {
                    $('#cb_edit_camp option[name=' + admin.CampaignRoleCountryInfo[0].CampaignRoleInfo.CampaignInfo.Id + ']').attr("selected", "selected");
                    $('.ddlCampaign_edit .customStyleSelectBoxInner').html(admin.CampaignRoleCountryInfo[0].CampaignRoleInfo.CampaignInfo.Name);
                    $.each(admin.CampaignRoleCountryInfo, function (i, val) {
                        $.each(val.CountryList, function (i, val_country) {
                            $('.for_edit #country' + val_country.Id + ' .label_check').addClass('c_on');
                            $('.for_edit .list_count input[name=' + val_country.Id + ']').attr('checked', true);
                        });
                    });
                }
                else {
                    $('#cb_edit_camp option[name=0]').attr("selected", "selected");
                    $('.ddlCampaign_edit .customStyleSelectBoxInner').html($('#cb_edit_camp option[name=0]').val());
                }
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in authenticateduser/list/summary.json ->" + xerror);
            }
        }
    });

    $('#btnCancelEdit').click(function (e) {
        $('.rows_user_hover .bar').addClass('hide');
        $('.rows_users').removeClass('rows_user_hover');
        $("#edit_super_admin").addClass('hide');
        return false;
    });
}
function showNewAdmin() {
    $('.controls_new').addClass('hide');
    $('.lbl_new').removeClass('hide');
    $('.ddl_user_new').addClass('user_view').removeClass('user_edit');
    $('.for_new').addClass('user_view').removeClass('user_edit');
    $('.list_campaign_cb').addClass('user_view').removeClass('user_edit');    
    $('.box_super_admin').addClass('hide');
    $('#new_super_admin').removeClass('hide');
    $('#btn_create_new_acc').addClass('hide');
    $('#btn_update_new_acc').removeClass('hide');
    $('#tr_username').removeClass('hide');
    $('.red').removeClass('red');
    $('.rows_users.rows_user_hover').removeClass('rows_user_hover');
    $('.bar').addClass('hide');
    $('.list_row_users').jScrollPane({ animateScroll: true });
    $('.div_countries').jScrollPane({ animateScroll: true });
    $('#btnCancelNew').click(function (e) {
        $("#new_super_admin").addClass('hide');
        return false;
    });
}
function checkMail2() {
    var mail_user = $('#email_user').val();
    var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (emailReg.test(mail_user)) {
        // TODO: email is true
        $('#lblRequired_1').removeClass('red');
        return true;
    }
    else {
        $('#email_label').addClass('red');
        $('#lblRequired_1').html('Email address not on file');
        $('#lblRequired_1').addClass('red');
        return false;
    } //Please complete required fields
}
function checkEmty2() {
    var co = true;
    var firtname = $('#first_name_user').val();
    var mail_user = $('#email_user').val();
    var lastname = $('#last_name_user').val()
    var phone_user = $('#phone_user').val();
    var zone = $('#timeZone_user').val();
    var roll = $('#role_user').val();

    //check first name
    if (firtname == '') {
        $('#first_name_label').addClass('red');
        co = false;
    }
    //check last name
    if (lastname == '') {
        $('#last_name_label').addClass('red');
        co = false;
    }
    if (mail_user == '') {
        $('#email_label').addClass('red');
        co = false;
    }
    if (phone_user == '') {
        $('#phone_label').addClass('red');
        co = false;
    }
    //check timeZone
    if (zone == 'Select Time Zone') {
        $('#timeZone_label').addClass('red');
        co = false;
    }
    if (roll == 'Select Role') {
        $('#role_label').addClass('red');
        co = false;
    }
    //check country
    var flag = false;
    $('.for_new input.case_main').each(function () {
        if ($(this).is(':checked')) {
            flag = true;
            $('#countries_label').removeClass('red');
        }
    });
    if (!flag) {
        $('#countries_label').addClass('red');
        co = false;
    }
    return co;
}
function resetForm() {
    $('#first_name_user').val('');
    $('#last_name_user').val('');
    $('#email_user').val('');
    $('#phone_user').val('')
    $('#ddl_user_new option:first-child').attr('selected', 'selected');
    $('.ddl_user_new.user_edit .customStyleSelectBoxInner').html($('#ddl_user_new option:first-child').val());
    $('.div_countries.user_edit input.case_main').attr('checked', false);
    $('.div_countries.user_edit .label_check').removeClass('c_on');
    $('.list_campaign_cb.user_edit input.case_main').attr('checked', false);
    $('.list_campaign_cb.user_edit .label_check').removeClass('c_on');
}
function showNewAdmin2(id) {
    $('.ddl_user_new').addClass('user_edit').removeClass('user_view');
    $('.for_new').addClass('user_edit').removeClass('user_view');
    $('.list_campaign_cb').addClass('user_edit').removeClass('user_view');
    if (id == '') {
        resetForm();
    }
    else {
        $.ajax({
            url: gb_servicePath + '/authenticateduser/ID/' + id + '.json',
            crossDomain: "true",
            type: "GET",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    var admin = data.ReturnData;
                    $('#first_name_user').val(admin.FirstName);
                    $('#last_name_user').val(admin.LastName);
                    $('#email_user').val(admin.EmailAddress);
                    $('#phone_user').val(admin.PhoneNumber);
                    $('#cb_timezone_new option[name=' + admin.TimeZoneID + ']').attr("selected", "selected");
                    $('.cus_ddl select_time .customStyleSelectBoxInner').html($('#cb_timezone_new option[name=' + admin.TimeZoneID + ']').val());

                    $('#ddl_user_new option[name=' + admin.UserRoles[0].RoleType + ']').attr("selected", "selected");
                    $('.ddl_user_new .customStyleSelectBoxInner').html($('#ddl_user_new option[name=' + admin.UserRoles[0].RoleType + ']').val());

                    $('.list_campaign_cb .label_check').removeClass('c_on');
                    $('.list_campaign_cb .list_count input').attr('checked', false);
                    $('.for_new .label_check').removeClass('c_on');
                    $('.for_new .list_count input').attr('checked', false);

                    $.each(admin.CampaignRoleCountryInfo, function (i, val) {
                        $('.list_campaign_cb #' + val.CampaignRoleInfo.CampaignInfo.Id + ' .label_check').addClass('c_on');
                        $('.list_campaign_cb .list_count input[name=' + val.CampaignRoleInfo.CampaignInfo.Id + ']').attr('checked', true);

                        $.each(val.CountryList, function (i, val_country) {
                            $('.for_new #country' + val_country.Id + ' .label_check').addClass('c_on');
                            $('.for_new .list_count input[name=' + val_country.Id + ']').attr('checked', true);
                        });
                    });


                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in /authenticateduser/ID/' + selectedRowKey + '.json ->" + xerror);
                }
            }
        });
    }
    $('.box_super_admin').addClass('hide');
    //$('#new_super_admin').addClass('hide');
    $('#new_super_admin').removeClass('hide');
    $('.lbl_new').addClass('hide');
    $('.red').removeClass('red');
    $('.controls_new').removeClass('hide');
    $('#btn_create_new_acc').removeClass('hide');
    $('#btn_update_new_acc').addClass('hide');
    $('#tr_username').addClass('hide');
    $('.rows_users.rows_user_hover').removeClass('rows_user_hover');
    $('.bar').addClass('hide');
    $('.list_row_users').jScrollPane({ animateScroll: true });
    $('.div_countries').jScrollPane({ animateScroll: true });
}
    
